package jwttool

import (
	"errors"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
)

type Claims struct {
	UserId string
	jwt.RegisteredClaims
}

const Issuer = "@iota"
const EXPIRATION = 2 * time.Hour

var SigningKey = []byte("acc0081")

// 生成token
func Gentoken(id string) (string, error) {
	claims := &Claims{
		UserId: id,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    Issuer,                                         //颁发者
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(EXPIRATION)), //过期时间
			IssuedAt:  jwt.NewNumericDate(time.Now()),                 //颁发时间
			NotBefore: jwt.NewNumericDate(time.Now()),                 // 生效时间
			ID:        "",                                             // 黑白名单
		},
	}
	// 生成token对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 生成token 字符串
	return token.SignedString(SigningKey)
}

// 解析token
func ParseToken(tokenStr string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
		return SigningKey, nil
	})
	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}

	return nil, errors.New("invalid token")
}

// 编写中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenStr := c.Request.Header.Get("Authorization")
		if tokenStr == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"code": 0,
				"msg":  "请求头中auth为空",
			})
			return
		}

		mc, err := ParseToken(tokenStr)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"code": 0,
				"msg":  "无效的Token",
			})
			return
		}

		// UserId
		c.Set("UserId", mc.UserId)
		c.Next() // 后续的处理函数可以用过c.Get("UserId")来获取当前请求的用户信息
	}
}
